<template>
  <div class="jeecg-basic-table visit-list-view">
    <div class="tip">
      <span>访客列表</span>
      <span class="tip-img"></span>
    </div>
    <div class="jeecg-search-layer">
      <a-form ref="form" :model="queryParam">
        <a-row :gutter="[16, 16]">
          <a-col :span="8">
            <a-form-item label="站点">
              <a-select v-model:value="queryParam.stationCode" allowClear placeholder="请选择站点">
                <template v-for="(item, index) in stationList" :key="index">
                  <a-select-option :value="item.stationCode">
                    {{ item.name }}
                  </a-select-option>
                </template>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :span="8">
            <a-form-item label="登记状态">
              <a-select v-model:value="queryParam.visitStatus" allowClear placeholder="请选择登记状态">
                <a-select-option :value="0">未确认</a-select-option>
                <a-select-option :value="1">已确认</a-select-option>
                <a-select-option :value="2">已离场</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :span="8">
            <a-form-item label="来访者">
              <a-input v-model:value="queryParam.visitor" allowClear placeholder="请输入来访者" />
            </a-form-item>
          </a-col>
          <a-col :span="8">
            <a-form-item label="来访电话">
              <a-input v-model:value="queryParam.visitorTel" allowClear placeholder="请输入来访电话" />
            </a-form-item>
          </a-col>
          <a-col :span="8">
            <a-form-item label="访问时间">
              <a-range-picker
                v-model:value="stationDateTime"
                format="YYYY-MM-DD HH:mm:ss"
                valueFormat="YYYY-MM-DD HH:mm:ss"
                style="width: 100%"
                show-time
              />
            </a-form-item>
          </a-col>
        </a-row>
        <a-row>
          <a-col :span="24" style="text-align: right">
            <a-form-item>
              <a-button type="primary" @click="onSearch">查询</a-button>
              <a-divider type="vertical" />
              <a-button type="primary" @click="onAdd('')">新增</a-button>
            </a-form-item>
          </a-col>
        </a-row>
      </a-form>
    </div>
    <div class="jeecg-table-view">
      <a-table :loading="loading" rowKey="id" :dataSource="dataSource" :columns="columns" :pagination="false" :scroll="{ y: 560 }">
        <template v-slot:bodyCell="{ column, record, index }">
          <template v-if="column.dataIndex == 'action'">
            <a @click="handleDetail(record)">详情</a>
            <!-- <a-divider type="vertical" /> -->
          </template>
        </template>
      </a-table>
      <Pagination
        v-model:current="ipagination.current"
        :pageSize="ipagination.pageSize"
        :total="ipagination.total"
        :showTotal="ipagination.showTotal"
        show-less-items
        show-quick-jumper
        @change="handlePageChange"
        @showSizeChange="onShowSizeChange"
      />
    </div>
    <!-- <div class="jeecg-table-view">
      <template v-if="mode == 'list'">
        <BasicTable @register="registerTable">
          <template #tableTitle> </template>
          <template #action="{ record }">
            <TableAction :actions="getTableAction(record)" />
          </template>
        </BasicTable>
      </template>
    </div> -->
    <FormDrawer ref="formDrawer" @oks="onInit" :stationList="stationList" />
  </div>
</template>

<script lang="ts">
import { defineComponent, onActivated } from 'vue';
export default defineComponent({
  name: 'visitLists',
});
</script>

<script lang="ts" setup>
import { ref, watch, getCurrentInstance, onMounted, nextTick } from 'vue';
import { visitPageApi, visitListApi, visitDeleteApi } from '/@/api/visit/index';
import { stationListApi } from '/@/api/station/index';
import { Pagination } from 'ant-design-vue';
import FormDrawer from './components/form.vue';
import { useGo } from '/@/hooks/web/usePage';
import { usePermission } from '/@/hooks/web/usePermission';
import { useUserStore } from '/@/store/modules/user';
import { ajaxGetDictItems } from '/@/utils/dict';
import { useListPage } from '/@/hooks/system/useListPage';
import { BasicTable, TableAction, ActionItem } from '/@/components/Table';
import { BasicColumn } from '/@/components/Table';
import { listNoCareTenant } from '../system/user/user.api';

let userList = ref([]);

let { proxy } = getCurrentInstance();

const userStore = useUserStore();

const { isDisabledAuth } = usePermission();

const go = useGo();

let loading = ref(false);
let stationDateTime = ref([]);

let queryParam = ref({
  // 站点编码
  stationCode: '',
  // 到访申请状态
  visitStatus: '',
  // 开始时间
  visitTimeStart: '',
  // 结束时间
  visitTimeEnd: '',
  // 来访者
  visitor: '',
  // 来访电话
  visitorTel: '',
});

let visitDateTime = ref([]);
let regionList = ref([]);
let ipagination = ref({
  current: 1,
  pageSize: 10,
  pageSizeOptions: ['10', '20', '30'],
  showTotal: (total, range) => {
    return range[0] + '-' + range[1] + ' 共' + total + '条';
  },
  showQuickJumper: true,
  showSizeChanger: true,
  total: 0,
});
// 数据源
let dataSource = ref([]);
// 字段
let columns: BasicColumn[] = [
  {
    title: '序号',
    dataIndex: 'index',
    key: 'id',
    width: 60,
    align: 'center',
    customRender: (t, r, index) => {
      return (ipagination.value.current - 1) * ipagination.value.pageSize + t.renderIndex + 1;
    },
  },
  {
    title: '访问记录编号',
    align: 'center',
    dataIndex: 'visitId',
  },
  {
    title: '归属站点',
    align: 'center',
    dataIndex: 'stationCode',
    customRender: ({ text }) => {
      return stationList.value.find((_) => _.stationCode === text)?.name;
    },
  },
  {
    title: '登记状态',
    align: 'center',
    dataIndex: 'visitStatus',
    customRender: ({ text }) => {
      const CONFIG = {
        0: '未确认',
        1: '已确认',
        2: '已离场',
      };
      return CONFIG[text];
    },
  },
  {
    title: '离场时间',
    align: 'center',
    dataIndex: 'leaveTime',
  },
  {
    title: '访客姓名',
    align: 'center',
    dataIndex: 'visitor',
    // customRender: ({ text }) => {
    //   return userList.value.find((_) => _.username === text)?.realname;
    // },
  },
  {
    title: '访客电话',
    align: 'center',
    dataIndex: 'visitorTel',
  },
  {
    title: '到访目的',
    align: 'center',
    dataIndex: 'visitReason',
  },
  {
    title: '被访人员',
    align: 'center',
    dataIndex: 'visitEmployee',
    customRender: ({ text }) => {
      return userList.value.find((_) => _.username === text)?.realname;
    },
  },
  {
    title: '访问时间',
    align: 'center',
    dataIndex: 'visitTime',
  },
  {
    title: '操作',
    dataIndex: 'action',
    align: 'center',
  },
];

const { prefixCls, tableContext, onExportXls, onImportXls } = useListPage({
  designScope: 'visit-list',
  tableProps: {
    title: '访客列表',
    api: visitListApi,
    columns,
    size: 'small',
    formConfig: {
      // labelWidth: 200,
      // schemas: searchFormSchema,
    },
    actionColumn: {
      width: 190,
      fixed: 'right',
    },
  },
});

watch(
  () => stationDateTime.value,
  (dateLists) => {
    let startTime = '';
    let endTime = '';
    if (dateLists && dateLists.length > 0) {
      let [a, b] = dateLists;
      startTime = a;
      endTime = b;
    } else {
      startTime = '';
      endTime = '';
    }
    Object.assign(queryParam.value, {
      visitTimeStart: startTime,
      visitTimeEnd: endTime,
    });
  }
);
/**
 * 操作栏
 */
function getTableAction(record): ActionItem[] {
  return [
    {
      label: '详情',
      onClick: onAdd.bind(null, record),
      // ifShow: () => hasPermission('system:user:edit'),
    },
    // {
    //   label: '决策配置',
    //   onClick: handleDecision.bind(null, record),
    // },
    // {
    //   label: '删除',
    //   onClick: handleDelete.bind(null, record),
    // },
  ];
}

const [registerTable, { reload, updateTableDataRecord }, { rowSelection, selectedRows, selectedRowKeys }] = tableContext;

// 列表模式 => list /卡片模式 => card
let mode = ref('list');

// 站点列表
let stationList = ref([]);

// 访客列表
let visitList = ref([]); //ref(userStore.getvisitList);

watch(
  () => queryParam.value.visitId,
  (dataValue) => {
    let data = visitList.value.find((k) => k.id == dataValue);
    if (data) {
      Object.assign(queryParam.value, {
        visitCode: data.visitCode,
        name: data.name,
      });
    }
  }
);

watch(
  () => visitDateTime.value,
  (dateLists) => {
    let startTime = '';
    let endTime = '';
    if (dateLists && dateLists.length > 0) {
      let [a, b] = dateLists;
      startTime = a;
      endTime = b;
    } else {
      startTime = '';
      endTime = '';
    }
    Object.assign(queryParam.value, {
      // 创建时间结束
      createTimeEnd: startTime,
      // 创建时间开始
      createTimeStart: endTime,
    });
  }
);

watch(
  () => mode.value,
  (e) => {
    if (e == 'list') {
      ipagination.value.pageSize = 10;
    } else {
      ipagination.value.pageSize = 9;
    }
    onInit();
  }
);

/**
 * 初始化数据列表
 */
function onInit() {
  let { current, pageSize } = ipagination.value;
  let data = {
    current,
    size: pageSize,
  };
  let keys = Object.keys(queryParam.value);
  Object.values(queryParam.value).map((_, i) => {
    if (_ !== '') {
      data[keys[i]] = _;
    }
  });
  delete data['visitId'];

  loading.value = true;
  visitPageApi(data).then((res) => {
    loading.value = false;
    let { records, size, current, total } = res;
    Object.assign(ipagination.value, {
      current,
      pageSize: size,
      total,
    });
    dataSource.value = records;
  });
  ajaxGetDictItems('visit_type');
}

function initvisit() {
  visitListApi({}).then((res: any) => {
    visitList.value = res;
  });
}

/**
 * 切换当前页数
 */
function handlePageChange(page) {
  ipagination.value.current = page;
  onInit();
}

function onShowSizeChange(current, pageSize) {
  Object.assign(ipagination.value, { current, pageSize });
  onInit();
}

/**
 * 打开新增弹窗
 */
function onAdd(row) {
  proxy.$refs.formDrawer.showDrawer(row);
}

/**
 * 查看详情
 */
function handleDetail({ id }) {
  proxy.$refs.formDrawer.visible = true;
  nextTick(() => {
    proxy.$refs.formDrawer.init(id);
  });
}

/**
 * 配置访客决策
 */
function handleDecision({ visitCode }) {
  proxy.$refs.decisionDrawer.visible = true;
  nextTick(() => {
    proxy.$refs.decisionDrawer.init(visitCode);
  });
}

/**
 * 删除数据
 */
function handleDelete({ id }) {
  visitDeleteApi({ id }).then((res) => {
    onInit();
  });
}

/**
 * 跳转到plc编辑器
 */
function onOpenPlc({ id }) {
  go(`/meta/index?id=${id}`);
}

/**
 * 预览PLC图
 */
function onPreview({ id }) {
  // let args = [`id=${id}`, `r=${Date.now() + ''}`];
  // go(`/metaPreview?${args.join('&')}`);
  go(`/water/visit/device?id=${id}`);
}

/**
 * 搜索数据
 */
function onSearch() {
  ipagination.value.current = 1;
  onInit();
}

/**
 * 切换卡片或者列表模式
 */
function onChangeMode() {
  mode.value = mode.value === 'list' ? 'card' : 'list';
}
onMounted(async () => {
  stationList.value = await stationListApi({});
  const res = await listNoCareTenant({});
  userList.value = res.records;
  onInit();
});

// onActivated(() => {
//   initProjectList();
//   initvisit();
//   onInit();
// });
</script>

<style lang="less" scoped>
.visit-list-view {
  margin: 12px;
  background: #fff;
  .tip {
    width: 100%;
    height: 44px;
    padding: 0 0 0 43.3px;
    background: url('@/assets/images/img-17.png') no-repeat;
    background-size: 100% 100%;
    line-height: 44px;
    span {
      font-size: 16px;
      color: #fff;
    }
  }
  .jeecg-search-layer {
    margin: 0 0 17px;
    padding: 12px 15px;
    background: #fff;
    border-radius: 8px;
    .ant-form {
      max-width: auto;
      .ant-form-item {
        margin-bottom: 24px;
      }
      :deep(.ant-col) {
        width: auto;
      }
    }
  }
  .jeecg-table-view {
    margin: 24px;
    .card-list {
      padding: 0 0 24px;
    }
    .ant-pagination {
      padding: 12px 0;
    }
  }
}
</style>
